"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Eye, EyeOff, Loader, Lock } from "lucide-react";
import {
  UpdateProfilePasswordFormData,
  UpdateProfilePasswordSchema,
} from "@/schemas/profile";
import { useMutation } from "@tanstack/react-query";
import { UpdateProfilePasswordAction } from "@/actions/profile";
import { useEffect, useState } from "react";
import { useSession, signOut } from "next-auth/react";
import Image from "next/image";
import Input from "@/components/custom-ui/input";
import { useTranslations } from "next-intl";

export default function Page() {
  const t = useTranslations("profilePages");
  const tZod = useTranslations("zod");
  const { data: session } = useSession();
  const [pwdShow, setPwdShow] = useState(false);
  const [newPwdShow, setNewPwdShow] = useState(false);
  const form = useForm<UpdateProfilePasswordFormData>({
    resolver: zodResolver(UpdateProfilePasswordSchema(tZod)),
    defaultValues: {
      id: "",
      password: "",
      new_password: "",
    },
  });
  useEffect(() => {
    if (session?.user.id) {
      form.setValue("id", session.user.id);
    }
  }, [session?.user.id, form]);

  const mutation = useMutation({
    mutationFn: UpdateProfilePasswordAction,
    onSuccess: (data) => {
      if (data.success) {
        toast.success(data.success);
      }
      if (data.error) {
        toast.error(data.error);
      }
    },
    onError: (error) => {
      toast.error(error.message);
    },
  });

  const onSubmit = async (values: UpdateProfilePasswordFormData) => {
    const r = await mutation.mutateAsync(values);
    if (r.success) {
      signOut({ redirectTo: "/auth/login" });
    }
  };
  return (
    <div className="flex flex-col gap-6 w-full">
      <div className="flex justify-center items-center">
        <Image
          src="/images/password.svg"
          width={96}
          height={96}
          alt={"Password"}
          className="rounded-xl shadow-[0_0_10px_2px_rgba(0,0,0,0.2)]"
        />
      </div>
      <Form {...form}>
        <form
          onSubmit={form.handleSubmit(onSubmit)}
          className="w-full space-y-6"
        >
          <FormField
            control={form.control}
            name="password"
            render={({ field }) => (
              <FormItem>
                <FormLabel className="text-muted-foreground">{t("password")}</FormLabel>
                <FormControl>
                  <Input
                    type={!pwdShow ? "password" : "text"}
                    placeholder="******"
                    {...field}
                    startIcon={<div className="w-10 flex justify-center"><Lock className="h-4 w-4" /></div>}
                    endIcon={
                      <div
                        onClick={() => setPwdShow(!pwdShow)}
                        className="w-12 flex justify-center cursor-pointer"
                      >
                        {pwdShow ? (
                          <Eye className="h-4 w-4" />
                        ) : (
                          <EyeOff className="h-4 w-4" />
                        )}
                      </div>
                    }
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="new_password"
            render={({ field }) => (
              <FormItem>
                <FormLabel className="text-muted-foreground">
                  {t("newPassword")}
                </FormLabel>
                <FormControl>
                  <Input
                    type={!newPwdShow ? "password" : "text"}
                    placeholder="******"
                    {...field}
                    startIcon={<div className="w-10 flex justify-center"><Lock className="h-4 w-4" /></div>}
                    endIcon={
                      <div
                        onClick={() => setNewPwdShow(!newPwdShow)}
                        className="w-10 flex justify-center cursor-pointer"
                      >
                        {newPwdShow ? (
                          <Eye className="h-4 w-4" />
                        ) : (
                          <EyeOff className="h-4 w-4" />
                        )}
                      </div>
                    }
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <Button
            className="w-full h-12 cursor-pointer select-none"
            type="submit"
            disabled={mutation.isPending}
          >
            {mutation.isPending ? <Loader className="animate-spin" /> : null}
            {t("updatePassword")}
          </Button>
        </form>
      </Form>
    </div>
  );
}
